package com.douguo.recipe.sina;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

import android.content.Context;

public abstract class UploadFileCallback extends Callback {

	String end = "\r\n";
	String twoHyphens = "--";
	private static String BOUNDARY = "*****";

	@Override
	public Context getContext() {
		return null;
	}

	public abstract List<FormFile> getFile();

	public abstract Param getFormKeyValue();

	@Override
	public Param getHeader() {
		Param p = new Param();
		p.append("Connection", "Keep-Alive");
		p.append("Charset", "UTF-8");
		p.append("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
		return p;
	}

	@Override
	public byte[] getPostParam() {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);

		List<FormFile> files = getFile();
		for (FormFile f : files) {
			StringBuilder split = new StringBuilder();
			split.append(twoHyphens);
			split.append(BOUNDARY);
			split.append(end);
			split.append("Content-Disposition: form-data;name=\"");
			split.append(f.getFormname());
			split.append("\";filename=\"");
			split.append(f.getFilname());
			split.append("\"");
			split.append(end);

			split.append("Content-Type:");
			split.append(f.getContentType());
			split.append(end);
			split.append(end);

			try {
				dos.write(split.toString().getBytes());
				dos.write(f.getData(), 0, f.getData().length);
				dos.write(end.getBytes("utf-8"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return baos.toByteArray();
	}
}
